package com.smfx.yxt.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import com.smfx.yxt.common.Const;
import com.smfx.yxt.common.MenuConst;
import com.smfx.yxt.common.RspResult;
import com.smfx.yxt.common.enums.FunctionRoomStatus;
import com.smfx.yxt.common.enums.Status;
import com.smfx.yxt.common.enums.WorkApprovalType;
import com.smfx.yxt.daoSqlserver.FunctionRoomApplyMapper;
import com.smfx.yxt.daoSqlserver.ReqFunctionRoomApplyMapper;
import com.smfx.yxt.daoSqlserver.TeacherInfoMapper;
import com.smfx.yxt.daoSqlserver.WorkApprovalConfMapper;
import com.smfx.yxt.model.FunctionRoomApply;
import com.smfx.yxt.model.ReqFunctionRoomApply;
import com.smfx.yxt.model.TeacherInfo;
import com.smfx.yxt.model.WorkApprovalConf;
import com.smfx.yxt.page.Page;
import com.smfx.yxt.reqVo.FunctionRoomApplyReqVO;
import com.smfx.yxt.reqVo.FunctionRoomQueryVO;
import com.smfx.yxt.service.IFunctionRoomApplyService;
import com.smfx.yxt.utils.BeanUtils;
import com.smfx.yxt.utils.PropertiesUtil;
import com.smfx.yxt.view.FunctionRoomApplyView;
import com.smfx.yxt.wechat.utils.TemplateUtil;

@Service("functionRoomApplyService")
public class FunctionRoomApplyServiceImpl implements IFunctionRoomApplyService {

	@Autowired
	private FunctionRoomApplyMapper functionRoomApplyMapper;
	@Autowired
	private ReqFunctionRoomApplyMapper reqFunctionRoomApplyMapper;
	@Autowired
	private WorkApprovalConfMapper workApprovalConfMapper;
	@Autowired
	private TeacherInfoMapper teacherInfoMapper;
	
	@Override
	public RspResult addApply(FunctionRoomApply record) {
		functionRoomApplyMapper.insertSelective(record);
		ReqFunctionRoomApply req = new ReqFunctionRoomApply();
		req.setApplyId(record.getId());
		req.setTeacherId(record.getApplyerId());
		req.setTeacherName(record.getApplyer());
		req.setStatus(record.getStatus());
		reqFunctionRoomApplyMapper.insertSelective(req);
		ThreadExecute(record);
		return new RspResult(Status.SUCCESS);
	}

	@Override
	public FunctionRoomApply selectByPrimaryKey(Integer id) {
		return functionRoomApplyMapper.selectByPrimaryKey(id);
	}

	@Override
	public FunctionRoomApplyView selectViewById(Integer id) {
		FunctionRoomApply apply = functionRoomApplyMapper.selectByPrimaryKey(id);	
		FunctionRoomApplyView viewApply = BeanUtils.copyAs(apply, FunctionRoomApplyView.class);
		List<ReqFunctionRoomApply> reqList = reqFunctionRoomApplyMapper.selectListByApplyId(id);
		viewApply.setReqList(reqList);
		return viewApply;
	}

	@Override
	public RspResult updateAudit(FunctionRoomApplyReqVO reqVo, TeacherInfo teacher) {
		FunctionRoomApply apply = functionRoomApplyMapper.selectByPrimaryKey(reqVo.getApplyId());
		if(FunctionRoomStatus.AGREE.getCode().equals(reqVo.getStatus())) {
			FunctionRoomApply coincideApply = functionRoomApplyMapper.selectCoincideApply(apply);
			if(coincideApply != null) {
				return new RspResult(Status.FUNCTION_ROOM_COINCIDE, coincideApply);
			}
		}
		ReqFunctionRoomApply req = new ReqFunctionRoomApply();
		req.setApplyId(reqVo.getApplyId());
		req.setTeacherId(teacher.getId());
		req.setTeacherName(teacher.getName());
		req.setRemarks(reqVo.getRejectReason());
		req.setStatus(reqVo.getStatus());
		reqFunctionRoomApplyMapper.insertSelective(req);
		if(!FunctionRoomStatus.APPLYER_CANCEL.getCode().equals(reqVo.getStatus())) {
			apply.setApprover(teacher.getName());
			apply.setApproverId(teacher.getId());
		}else {
			if(apply.getApplyerId().intValue() != teacher.getId()) {
				return new RspResult(Status.NO_POWER);
			}
		}
		apply.setStatus(reqVo.getStatus());
		apply.setRejectReason(reqVo.getRejectReason());
		functionRoomApplyMapper.updateByPrimaryKeySelective(apply);
		ThreadExecute(apply);
		return new RspResult(Status.SUCCESS);
	}

	@Override
	public List<FunctionRoomApply> selectListByPage(Page<FunctionRoomApply> page) {
		return functionRoomApplyMapper.selectListByPage(page);
	}

	@Override
	public List<FunctionRoomApply> selectAuditSuccessListByDate(FunctionRoomQueryVO vo) {
		return functionRoomApplyMapper.selectAuditSuccessListByDate(vo);
	}

	void ThreadExecute(FunctionRoomApply apply) {
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
	        @Override
	        public void afterCommit() {
	        	String reqUrl = Const.BASEPATH + Const.TEACHER_ROLE + 
						MenuConst.FUNCTION_ROOM + "/detail/" + apply.getId();
	        	String approvalType = "功能室申请";
	        	if(FunctionRoomStatus.PENDING.getCode().equals(apply.getStatus())) {
	        		String templateId = PropertiesUtil.getProperty("work_approval_apply_template");
	        		WorkApprovalConf conf = workApprovalConfMapper.selectByItemCode(
	        				WorkApprovalType.ROOM_APPROVAL.getCode());
					List<TeacherInfo> teacherList = teacherInfoMapper.selectListByIds(
							Arrays.asList(conf.getApprovalerId().split(",")));
					for(TeacherInfo teacher : teacherList) {
						TemplateUtil.approvalApplySend(teacher.getOpenid2(), approvalType, apply.getApplyer(), 
								apply.getUseReason(), new Date(), templateId, reqUrl);
					}
	        	}else if(FunctionRoomStatus.AGREE.getCode().equals(apply.getStatus()) || 
	        			FunctionRoomStatus.REJECT.getCode().equals(apply.getStatus()) ||
	        			FunctionRoomStatus.APPROVER_CANCEL.getCode().equals(apply.getStatus())) {
	        		String templateId = PropertiesUtil.getProperty("work_approval_result_template");
	        		String title = "您好！您提交的功能室申请已经被审批";
	        		if(FunctionRoomStatus.APPROVER_CANCEL.getCode().equals(apply.getStatus())) {
	        			title = "您好！您申请到的功能室被审批人取消，请知悉";
	        		}
	        		TeacherInfo applyTeacher = teacherInfoMapper.selectByPrimaryKey(apply.getApplyerId());
					TemplateUtil.approvalResultSend(applyTeacher.getOpenid2(), title, approvalType, 
							FunctionRoomStatus.getValue(apply.getStatus()), new Date(), templateId, reqUrl);
	        	}
	        }
	    });
	}
}
